// 包名保持你工程里的原样
package no.nordicsemi.android.nrfmesh.auth.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;

import no.nordicsemi.android.nrfmesh.R;
import no.nordicsemi.android.nrfmesh.auth.data.AccountRepository;
import no.nordicsemi.android.nrfmesh.auth.session.SessionManager;
import no.nordicsemi.android.nrfmesh.auth.ui.login.LoginFragment;
import no.nordicsemi.android.nrfmesh.auth.ui.register.RolePickFragment;
import no.nordicsemi.android.nrfmesh.auth.util.CredentialStore;
import no.nordicsemi.android.nrfmesh.database.AppDatabase;
import no.nordicsemi.android.nrfmesh.widgets.CustomControlsActivity;
import no.nordicsemi.android.nrfmesh.widgets.UserMainActivity; // ← 你的用户主页

/**
 * AuthActivity（鉴权入口）
 *
 * - 决定打开 LoginFragment 还是 RolePickFragment
 * - 如果未显式跳过且会话已登录，直接进主界面
 * - 消费 SessionManager 的“一次性跳过自动登录”闩锁，保证登出后不会被顶回主界面
 */
public class AuthActivity extends AppCompatActivity {

    public static final String EXTRA_SKIP_AUTO_LOGIN = LoginFragment.EXTRA_SKIP_AUTO_LOGIN;
    public static final String EXTRA_START_DEST = "start_dest";
    public static final String DEST_LOGIN = "login";
    public static final String DEST_REGISTER = "register";

    /** 退出登录统一入口：清栈 + 跳过自动登录 + 起始页可选 */
    public static Intent intentFromLogout(android.content.Context ctx, boolean toRegister) {
        return new Intent(ctx, AuthActivity.class)
                .putExtra(EXTRA_SKIP_AUTO_LOGIN, true)
                .putExtra(EXTRA_START_DEST, toRegister ? DEST_REGISTER : DEST_LOGIN);
    }

    /** 切换账号入口（同样跳过自动登录） */
    public static Intent intentFromSwitch(android.content.Context ctx, boolean toRegister) {
        return new Intent(ctx, AuthActivity.class)
                .putExtra(EXTRA_SKIP_AUTO_LOGIN, true)
                .putExtra(EXTRA_START_DEST, toRegister ? DEST_REGISTER : DEST_LOGIN);
    }

    @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auth);
        setupAccountRepo();                 // 先注入仓库（VM 会加载账号列表 & 预填最近）
        handleNavigation(savedInstanceState, getIntent());
    }

    @Override protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        setupAccountRepo();                 // 新 Intent 也确保注入（幂等）
        handleNavigation(null, intent);
    }

    /** 注入 AccountRepository 给 AuthViewModel（幂等） */
    private void setupAccountRepo() {
        AuthViewModel vm = new ViewModelProvider(this).get(AuthViewModel.class);
        try {
            AccountRepository repo = new AccountRepository(
                    AppDatabase.getInstance(getApplicationContext()).localAccountDao(),
                    new CredentialStore(getApplicationContext()) // 我们已做失败回退
            );
            vm.attachAccountRepo(repo);
        } catch (Exception e) {
            // 不再中断流程：CredentialStore 已能回退；这里仅打日志
            Log.e("AuthActivity", "setupAccountRepo: init failed, fallback in use", e);
        }
    }

    /** 核心路由逻辑 */
    private void handleNavigation(@Nullable Bundle savedInstanceState, @Nullable Intent intent) {
        SessionManager session = new SessionManager(this);

        // A) 显式 Extra；B) 消费一次性闩锁（logout 时设置）
        boolean skipByExtra = intent != null && intent.getBooleanExtra(EXTRA_SKIP_AUTO_LOGIN, false);
        boolean skipByLatch = session.consumeSkipAutoLoginOnce(); // 消费后清除
        boolean skipAuto = skipByExtra || skipByLatch;

        // 未跳过且已登录 → 按角色直接进首页
        if (!skipAuto && session.isLoggedIn()) {
            Class<?> target = "USER".equals(session.getRole())
                    ? UserMainActivity.class
                    : CustomControlsActivity.class;
            startActivity(new Intent(this, target)
                    );
            finish();
            return;
        }

        // 决定起始页（默认 login；登出后建议传 register）
        String dest = intent != null ? intent.getStringExtra(EXTRA_START_DEST) : null;
        Fragment start = (DEST_REGISTER.equals(dest)) ? new RolePickFragment() : new LoginFragment();

        if (savedInstanceState == null) {
            int containerId = (findViewById(R.id.container) != null)
                    ? R.id.container : android.R.id.content; // 兜底容器
            getSupportFragmentManager().beginTransaction()
                    .replace(containerId, start, start.getClass().getSimpleName())
                    .commit();
        }
    }

    /** 兼容旧代码的跳转（注册流程等） */
    public void goTo(@NonNull Fragment fragment, boolean addToBackStack) {
        int containerId = (findViewById(R.id.container) != null)
                ? R.id.container : android.R.id.content;
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction()
                .setReorderingAllowed(true)
                .replace(containerId, fragment, fragment.getClass().getSimpleName());
        if (addToBackStack) tx.addToBackStack(fragment.getClass().getSimpleName());
        tx.commit();
    }

    public void goBack() {
        getSupportFragmentManager().popBackStack();
    }
}
